package org.ielse.frame.t.tz.parallax;

import org.ielse.frame.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

public class ParallaxLayoutInflater extends LayoutInflater {

	private ParallaxFragment fragment;

	protected ParallaxLayoutInflater(LayoutInflater original, Context newContext, ParallaxFragment fragment) {
		super(original, newContext);
		setFactory(new ParallaxFactory(this));

		this.fragment = fragment;
	}

	@Override public LayoutInflater cloneInContext(Context newContext) {
		return new ParallaxLayoutInflater(this, newContext, fragment);
	}

	class ParallaxFactory implements LayoutInflater.Factory {
		final int[] attrIds = { R.attr.alpha, R.attr.translation_x, R.attr.translation_y, R.attr.scale_x, R.attr.scale_y, R.attr.rotation };

		private LayoutInflater inflater;

		private final String[] sysViewPrefixs = new String[] { "android.widget.", "android.view.", };

		public ParallaxFactory(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override public View onCreateView(String name, Context context, AttributeSet attrs) {
			View view = createViewOrFailQuietly(name, context, attrs);

			if (view != null) {
				// obtain custom properties and related to the view
				setViewTag(view, context, attrs);
				fragment.getParallaxViews().add(view);
			}

			return view;
		}

		private void setViewTag(View view, Context context, AttributeSet attrs) {

			TypedArray a = context.obtainStyledAttributes(attrs, attrIds);
			if (a != null && a.length() > 0) {
				ParallaxViewTag tag = new ParallaxViewTag();
				tag.alpha = a.getFloat(0, 0);
				tag.translationX = a.getFloat(1, 0);
				tag.translationY = a.getFloat(2, 0);
				tag.scaleX = a.getFloat(3, 0);
				tag.scaleY = a.getFloat(4, 0);
				tag.rotation = a.getFloat(5, 0);

				view.setTag(R.id.parallax_view_tag, tag);
			}
			a.recycle();
		}

		private View createViewOrFailQuietly(String name, String prefix, Context context, AttributeSet attrs) {
			try {
				return inflater.createView(name, prefix, attrs);
			} catch (Exception e) {
				return null;
			}
		}

		private View createViewOrFailQuietly(String name, Context context, AttributeSet attrs) {
			// inflater custom view
			if (name.contains(".")) {
				return createViewOrFailQuietly(name, null, context, attrs);
			}
			// inflater system view
			for (String prefix : sysViewPrefixs) {
				View view = createViewOrFailQuietly(name, prefix, context, attrs);
				if (view != null) {
					return view;
				}
			}
			return null;
		}
	}

}
